<!-- @module level-record -->
<!-- @author: YunTao.Li -->
<!-- @description: 请假单 -->
<!-- @since: 2019-11-06 23:43:56 -->
<template>
  <el-card  class="box-card el-card-flex" >
    <div slot="header" class="clearfix">
        <span>
        <i class="el-icon-position"></i>
         查询信息
      </span>
    </div>
    <!-- form begin -->
    <div style="margin: 10px" >
    <el-form ref="queryForm" label-width="120px" class="div-header" :model="queryForm" size="mini">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="组织" prop="ouId">
              <!-- <OrgSelectTree v-model="queryForm.ouId" placeholder="组织" /> -->
              <OrgSelectTree ref="orgSelectRef" v-model="queryForm.orgCode" placeholder="组织机构" style="width: 240px" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="假期类型" prop="holidayType">
              <!-- <el-input v-model="queryForm.holidayType" placeholder="假期类型" /> -->
              <dictCombo
                style="width: 240px"
                v-model="queryForm.holidayType"
                dicttypeid="holidayType"
                name="holidayType"
                placeholder="假期类型"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="审批状态" prop="businessStatus">
              <dictCombo
                style="width: 240px"
                v-model="queryForm.businessStatus"
                dicttypeid="businessStatus"
                name="businessStatus"
                placeholder="审批状态"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                style="width: 240px"
                v-model="queryForm.startDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker
                style="width: 240px"
                v-model="queryForm.endDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="btnStyle">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getList()">查询</el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-refresh"
            @click="resetForm('queryForm')"
          >重置</el-button>
        </div>
    </el-form>
    </div>

    <!-- form end -->
      <div class="div-button">
        <el-button
          icon="el-icon-menu"
          type="primary"
          :disabled.sync="btn_view_disabled"
          size="mini"
          @click="onView"
        >查看详情</el-button>
        <el-button
          icon="el-icon-menu"
          type="success"
          :disabled.sync="btn_add_disabled"
          size="mini"
          @click="onAdd"
        >新增</el-button>
        <el-button
          icon="el-icon-menu"
          type="warning"
          size="mini"
          :disabled.sync="btn_edit_disabled"
          @click="onEdit"
        >编辑</el-button>
        <el-button
          icon="el-icon-menu"
          type="danger"
          size="mini"
          :disabled.sync="btn_delete_disabled"
          @click="handleDelete"
        >删除</el-button>
        <el-button
          icon="el-icon-menu"
          type="primary"
          size="mini"
          :disabled.sync="btn_submit_disabled"
          @click="handleSubmit"
        >提交</el-button>
        <el-button
          icon="el-icon-menu"
          type="info"
          size="mini"
          :disabled.sync="btn_drawback_disabled"
          @click="handleDrawback"
        >撤回</el-button>
        <el-button
          icon="el-icon-menu"
          type="primary"
          size="mini"
          :disabled.sync="btn_monitor_disabled"
          @click="onTaskMonitor"
        >监控</el-button>
      </div>

      <!-- table begin-->
      <div class="el-flex el-box-column " style="margin: 10px;">
        <el-card class="box-card el-card-flex" >
        <div slot="header" class="clearfix">
        <span>
        <i class="el-icon-position"></i>
          请假单
        </span>
        </div>

        <div class="el-flex el-box-column" style="margin: 5px;" >
          <el-table
            v-loading="listLoading"
            :data="leaveList"
            border
            fit
            highlight-current-row
            class="tableStyle"
            style="width: 100%"
            height="100%"
            @selection-change="onSelectChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="center" type="index" width="55" label="序号" />

            <!--单据编号-->
            <el-table-column align="center" label="单据编号" width="200px">
              <template slot-scope="scope">
                <span>{{ scope.row.leaveCode }}</span>
              </template>
            </el-table-column>

            <!--申请人-->
            <el-table-column align="center" label="申请人" width="80px">
              <template slot-scope="scope">
                <span>{{ scope.row.empName }}</span>
              </template>
            </el-table-column>

            <!--假期类别-->
            <el-table-column
              prop="holidayType"
              :formatter="dictFormatter"
              label-class-name="holidayType"
              align="center"
              label="假期类别"
              width="100px"
            >
              <!-- <template slot-scope="scope">
                <span>{{ scope.row.holidayType }}</span>
              </template>-->
            </el-table-column>

            <!--所属部门-->
            <el-table-column align="center" label="所属部门" width="200px">
              <template slot-scope="scope">
                <span>{{ scope.row.deptName }}</span>
              </template>
            </el-table-column>

            <!--请假天数-->
            <el-table-column align="center" label="请假天数" width="100px">
              <template slot-scope="scope">
                <span>{{ scope.row.days }}</span>
              </template>
            </el-table-column>

            <!--开始日期-->
            <el-table-column width="150px" align="center" label="开始日期">
              <template slot-scope="scope">
                <span>{{ scope.row.startDate | parseTime('{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>

            <!--结束日期-->
            <el-table-column width="150px" align="center" label="结束日期">
              <template slot-scope="scope">
                <span>{{ scope.row.endDate | parseTime('{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>

            <!--紧急联系人-->
            <el-table-column width="150px" label="紧急联系人" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.contact }}</span>
              </template>
            </el-table-column>

            <!--紧急联系电话-->
            <el-table-column width="150px" label="紧急联系电话" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.contactPhone }}</span>
              </template>
            </el-table-column>

            <!--审批状态-->
            <el-table-column
              prop="businessStatus"
              :formatter="dictFormatter"
              label-class-name="businessStatus"
              width="100px"
              label="审批状态"
              align="center"
            >
              <!-- <template slot-scope="scope">
                <span>{{ scope.row.businessStatus }}</span>
              </template>-->
            </el-table-column>

            <!--销假时间-->
            <el-table-column width="150px" align="center" label="销假时间">
              <!-- <template slot-scope="scope">
                <span>{{ scope.row.actualEndDate | parseTime('{y}-{m}-{d}') }}</span>
              </template>-->
            </el-table-column>

            <!--请假事由-->
            <el-table-column width="100px" label="请假事由" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.leaveDesc }}</span>
              </template>
            </el-table-column>

            <!--申请日期-->
            <el-table-column width="150px" align="center" label="申请日期">
              <template slot-scope="scope">
                <span>{{ scope.row.creationDate | parseTime('{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

      <!-- table end -->
      <pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page.sync="queryForm.page"
        :limit.sync="queryForm.limit"
        @pagination="getList"
      />
        </el-card>
      <inputForm ref="leaveInputDialog" @submitFunc="onSubmitForm" />
      <detailForm ref="leaveDetailDialog" />
      <historyMonitorList ref="hisMonitorDialog" />
    </div>

  </el-card>

</template>

<script>
import {
  leaveList,
  leaveAdd,
  leaveUpdate,
  leaveDelete,
  leaveSubmit,
  leaveDrawback
} from '@/api/attendance/leave-service'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import inputForm from './components/form/leave-form'
import detailForm from './components/form/leave-detail'
import dictCombo from './components/combo/dict-comb'
import OrgSelectTree from './components/combo/org-tree-select.vue'
import historyMonitorList from '@/views/attendance/components/taskMonitorList'

export default {
  components: {
    Pagination,
    inputForm,
    detailForm,
    dictCombo,
    OrgSelectTree,
    historyMonitorList
  },
  data() {
    return {
      height: 'calc(100% - 16px)',
      msg: '-',
      text_form: '查询信息',
      text_grid: '请假单',
      btn_add_disabled: false,
      btn_delete_disabled: true,
      btn_view_disabled: true,
      btn_edit_disabled: true,
      btn_submit_disabled: true,
      btn_drawback_disabled: true,
      btn_monitor_disabled: true,
      leaveList: [],
      listLoading: true,
      total: 0,
      selectedLength: 0,
      lastSelectedData: null,
      queryForm: {
        page: 1,
        limit: 20,
        ouId: '',
        orgCode: '',
        deptName: '',
        deptCode: '',
        empName: '',
        empCode: '',
        holidayType: '',
        businessStatus: '',
        startDate: null,
        endDate: null,
        queryRange: ''
      },
      inputRules: {}
    }
  },
  created() {
    // init query range
    const queryRange = localStorage.getItem('queryRange')
    this.queryForm.queryRange = queryRange
    if (queryRange === 'all') {
      this.btn_add_disabled = true
    } else if (queryRange === 'dept') {
      try {
        this.queryForm.deptName = localStorage.getItem('deptName')
        this.queryForm.deptCode = localStorage.getItem('deptCode')
        this.queryForm.orgCode = localStorage.getItem('orgCode')
      } catch (e) {
        console.log(e)
      }
    } else if (queryRange === 'person') {
      try {
        this.queryForm.empCode = localStorage.getItem('empCode')
        this.queryForm.empName = localStorage.getItem('empName')
        this.queryForm.orgCode = localStorage.getItem('orgCode')
      } catch (e) {
        console.log(e)
      }
    }

    // 初始化查询展示
    this.getList()
    // 初始化按钮diabled状态
    this.onSelectChange({})
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getList() {
      this.listLoading = true
      leaveList(this.queryForm).then(response => {
        this.leaveList = response.data.records
        this.total = response.data.total

        // 假loading 1秒后消失
        setTimeout(() => {
          this.listLoading = false
        }, 300)
      })
    },
    inputFormToggle(selectedData) {
      this.$refs.leaveInputDialog.toggele(selectedData)
    },
    detailFormToggle(selectedData) {
      this.$refs.leaveDetailDialog.toggele(selectedData)
    },
    handleAdd(data) {
      // 添加方法
      leaveAdd(data).then(response => {
        if (response.code === 200) {
          this.getList()
          // 清理子组件
          this.$refs.leaveInputDialog.resetFormData()
        } else {
          this.$message.error(response.message)
        }
      })
    },
    handleEdit(data) {
      // 编辑方法
      console.log('编辑 id :' + data.leaveId)
      leaveUpdate(data.leaveId, data).then(response => {
        if (response.code === 200) {
          this.getList()
          // 清理子组件
          this.$refs.leaveInputDialog.resetFormData()
        } else {
          this.$message.error(response.message)
        }
      })
    },
    handleDelete() {
      // 删除方法
      this.$confirm('确定要删除么?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          leaveDelete(this.lastSelectedData.leaveId).then(response => {
            if (response.code === 200) {
              this.$message({ type: 'success', message: '删除成功!' })
              this.getList()
            } else {
              this.$message.error(response.message)
            }
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    handleSubmit() {
      // 提交请假单
      this.$confirm('确定要提交么?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          leaveSubmit(
            this.lastSelectedData.leaveId,
            this.lastSelectedData
          ).then(response => {
            if (response.code === 200) {
              this.$message({ type: 'success', message: '提交成功!' })
              this.getList()
            } else {
              this.$message.error(response.message)
            }
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    handleDrawback() {
      this.$confirm('确定要撤回么?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          leaveDrawback(
            this.lastSelectedData.leaveId,
            this.lastSelectedData
          ).then(response => {
            if (response.code === 200) {
              this.$message({ type: 'success', message: '撤回成功!' })
              this.getList()
            } else {
              this.$message.error(response.message)
            }
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    onTaskMonitor() {
      const selectedData = JSON.parse(JSON.stringify(this.lastSelectedData))
      this.$refs.hisMonitorDialog.toggele(selectedData)
    },
    onAdd() {
      this.inputFormToggle(null)
    },
    onEdit() {
      const selectedData = JSON.parse(JSON.stringify(this.lastSelectedData))
      this.inputFormToggle(selectedData)
    },
    onView() {
      const selectedData = JSON.parse(JSON.stringify(this.lastSelectedData))
      this.detailFormToggle(selectedData)
    },
    onSubmitForm(data) {
      // 表单提交事件
      const submitLeaveId = data.leaveId
      if (
        submitLeaveId === null ||
        submitLeaveId === '' ||
        JSON.stringify(submitLeaveId) === '{}'
      ) {
        this.handleAdd(data)
      } else {
        this.handleEdit(data)
      }
    },
    onDataSync() {
      this.$message({ type: 'success', message: '开始同步' })
      var _this = this
      setTimeout(function() {
        _this.$message({ type: 'success', message: '同步完成' })
      }, 2000)
    },
    onSelectChange(selection) {
      this.selectedLength = selection.length || 0
      this.lastSelectedData = selection[this.selectedLength - 1]

      this.btn_delete_disabled = true
      this.btn_edit_disabled = true
      this.btn_submit_disabled = true
      this.btn_drawback_disabled = true
      this.btn_monitor_disabled = true
      this.btn_view_disabled = true

      // 先判断queryRange
      const queryRange = this.queryForm.queryRange
      if (queryRange === 'all' || queryRange === 'dept') {
        if (this.selectedLength && this.selectedLength === 1) {
          this.btn_view_disabled = false
        }
        return
      }

      if (!this.lastSelectedData) {
        return
      }

      // 根据审批状态改变按钮行为
      const businessStatus = this.lastSelectedData.businessStatus

      if (this.selectedLength && this.selectedLength === 1) {
        this.btn_view_disabled = false

        if (businessStatus && businessStatus === 'A') {
          // 待提交，草稿
          this.btn_edit_disabled = false
          this.btn_delete_disabled = false
          this.btn_submit_disabled = false
        } else if (businessStatus && businessStatus === 'B') {
          // 已撤回
          this.btn_edit_disabled = false
          this.btn_submit_disabled = false
          this.btn_monitor_disabled = false
        } else if (businessStatus && businessStatus === 'D') {
          // 已驳回
          this.btn_edit_disabled = false
          this.btn_submit_disabled = false
          this.btn_monitor_disabled = false
        } else if (businessStatus && businessStatus === 'C') {
          // 已提交，待审批
          this.btn_drawback_disabled = false
          this.btn_monitor_disabled = false
        } else if (businessStatus && businessStatus === 'E') {
          // 已提交，已审批
          this.btn_monitor_disabled = false
        } else if (businessStatus && businessStatus === 'F') { // 已提交，审批中
          this.btn_monitor_disabled = false
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "./index.scss";
.el-table__empty-text {
  line-height: 400px !important;
}
.el-table__empty-block {
  min-height: 350px !important;
}
// .el-table__body-wrapper，
// .is-scrolling-left{
//   height: 300px;
//   overflow: auto;
// }
</style>
